package cn.tianjindong.blog.common.utils;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class MailUtils {

	private String username;// 邮箱名，例如：tianjindong0804（就是去掉邮箱后的@xxx.com）
	private String password;// 邮箱的密码
	private String emailAddr;// 邮箱地址，例如：tianjindong0804@126.com
	private String mailhHost;// 邮箱服务器地址，例如：smtp.126.com
	// email 收件人邮箱地址
	// emailMsg 邮件内容

	/**
	 * 发送邮件
	 * 
	 * @param email
	 *            收件人邮箱
	 * @param subject
	 *            邮件的主题
	 * @param emailMsg
	 *            邮箱内容
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void sendMail(String email, String subject, String emailMsg) throws AddressException, MessagingException {
		// 1.创建一个程序与邮件服务器会话对象 Session

		Properties props = new Properties();
		//采用465端口，解决阿里云25端口禁用问题
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.socketFactory.port", "465");
		props.setProperty("mail.host", mailhHost);
		props.setProperty("mail.smtp.auth", "true");// 指定验证为true

		// 创建验证器
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				// 设置发件人邮箱即密码
				return new PasswordAuthentication(username, password);
			}
		};

		Session session = Session.getInstance(props, auth);

		// 2.创建一个Message，它相当于是邮件内容
		Message message = new MimeMessage(session);

		message.setFrom(new InternetAddress(emailAddr)); // 设置发送者

		message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者

		message.setSubject(subject);
		// message.setText("这是一封激活邮件，请<a href='#'>点击</a>");

		message.setContent(emailMsg, "text/html;charset=utf-8");

		// 3.创建 Transport用于将邮件发送

		Transport.send(message);
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmailAddr() {
		return emailAddr;
	}

	public void setEmailAddr(String emailAddr) {
		this.emailAddr = emailAddr;
	}

	public String getMailhHost() {
		return mailhHost;
	}

	public void setMailhHost(String mailhHost) {
		this.mailhHost = mailhHost;
	}
}
